<template>
  <!-- 商户  估价 属性价值配置 -->
  <div class="app-container">
    <el-form class="search-form-new" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="游戏名称" prop="gameId">
        <el-select v-model="queryParams.gameId" placeholder="请选择游戏名称" clearable size="small" @change="SearchDataGameChange">
          <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="字段名称" prop="fieldName">
        <el-input v-model="queryParams.fieldName" placeholder="请输入字段名称" clearable size="small" />
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <!-- <el-button type="success" icon="el-icon-plus" @click="handleAdd(0)">新增</el-button> -->
      </el-form-item>
    </el-form>
    <div class="table_box">
      <el-table stripe ref="table" v-loading="loading" :data="attributeList">
        <el-table-column label="系统编号" prop="id" width="120px" />
        <el-table-column label="游戏名称" prop="gameName"> </el-table-column>
        <el-table-column label="上级字段" prop="parentName"> </el-table-column>
        <el-table-column label="字段名称" prop="fieldName" />
        <!-- <el-table-column label="字段key" prop="systemKey" />
        <el-table-column label="三方id" prop="sid" /> -->
        <el-table-column label="价值" align="" prop="price" />
        <!-- <el-table-column label="是否展示" prop="isshow">
          <template slot-scope="scope">
            <el-switch @change="huishouChange($event, scope.row)" v-if="scope.row.parentId" v-model="scope.row.isshow"
              active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="2"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="回收页面" prop="hsisShow">
          <template slot-scope="scope">
            <el-switch @change="huishouChange($event, scope.row)" v-if="scope.row.parentId" v-model="scope.row.hsisShow"
              active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="2"></el-switch>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="排序" prop="sort" />
        <el-table-column label="扩展字段1" prop="kz1" />
        <el-table-column label="扩展字段2" prop="kz2" /> -->
        <el-table-column label="操作" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <!-- <span style="color:blue !important" @click="handleAdd(scope.row)">新增</span> -->
            <span style="color:blue !important;padding-left:20px !important;cursor: pointer;" @click="handleUpdate(scope.row)">修改</span>
            <span style="color:red !important;padding-left:20px !important;cursor: pointer;" @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加或修改游戏配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="reset">
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <!-- <el-form-item label="游戏名称" prop="gameId">
          <el-select v-model="form.gameId" @change="gameChange" placeholder="请选择游戏名称" :disabled="!topShow">
            <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="游戏名称" prop="">
          {{form.gameName}}
        </el-form-item>
        <el-form-item label="上级字段" prop="">
          {{form.parentName}}
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          {{form.fieldName}}
          <!-- <el-input v-model="form.fieldName" placeholder="请输入字段名称" /> -->
        </el-form-item>
        <el-form-item label="价值" prop="price">
          <el-input-number :step="5" :precision="0" v-model="form.price" placeholder="估价系数"></el-input-number>
          元
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="图标" prop="imgUrl">
          <el-upload class="avatar-uploader" :action="uploadImgUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :on-remove="handleRemove">
            <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="扩展字段1" prop="kz1">
          <el-input v-model="form.kz1" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="扩展字段2" prop="kz2">
          <el-input v-model="form.kz2" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="回收页面" prop="hsisShow" v-if="!topShow">
          <el-switch v-model="form.hsisShow" active-color="#13ce66" inactive-color="#ff4949" active-value="1"
            inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="是否展示" prop="isshow" v-if="!topShow">
          <el-switch v-model="form.isshow" active-color="#13ce66" inactive-color="#ff4949" active-value="1"
            inactive-value="2"></el-switch>
        </el-form-item> -->
        <!-- <el-switch @change="huishouChange($event,scope.row)" v-if="scope.row.parentId" v-model="scope.row.hsisShow" active-color="#13ce66" inactive-color="#ff4949" active-value="1"
              inactive-value="2" ></el-switch> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pinyin } from "pinyin-pro";
import gameDictionaryApi from "@/api/gameConfig/gameDictionary";
import gameListApi from "@/api/gameConfig/gameList";

import gujiaApi from "@/api/tenantApis/gujiaApi";
export default {
  name: "",
  components: {},
  data() {
    return {
      expandkeys: [], //展开的行
      carrierOptions: [], //当前游戏的运营商配置
      fieldTypes: [
        {
          name: "自定义",
          key: "",
          id: 1,
        },
        {
          name: "系统",
          key: "system",
          id: 2,
        },
        {
          name: "运营商",
          key: "carrier",
          id: 3,
        },
        {
          name: "大区",
          key: "group",
          id: 4,
        },
      ],
      searchGame: null,
      gameList: [],
      refreshTable: true,
      isExpandAll: false,
      topShow: true,
      uploadImgUrl: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 游戏配置表格数据
      attributeList: [],
      // 所有表格数据
      attributeListAll: [],
      // 所有父级数据  也就是不含最后一级的
      attributeListNoChild: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogVisible: false,
      // 查询参数
      queryParams: {
        gameId: null,
        fieldName: null,
      },
      // 表单参数
      form: {
        parentId: 0,
        imgUrl: "",
        hsisShow: "2",
        parentName: "",
        fieldName: "",
        systemKey: "",
        sort: 0,
        remark: "",
        sid: "",
        parentKey: "",
        gameType: "",
        gameName: "",
        type: "",
        carrier: "",
      },
      imgList: [],
      editRow: "",
      // 表单校验
      rules: {
        gameId: [{ required: true, message: "请选择游戏", trigger: "change" }],
        fieldName: [
          { required: true, message: "请输入字段名称", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.getGameList();
  },
  methods: {
    /** 查询游戏配置列表 */
    getList() {
      this.loading = true;
      gujiaApi.tenantAttributeSettings(this.queryParams).then((response) => {
        // let temp = this.handleTree(response.rows, "id");
        // this.attributeListAll = JSON.parse(JSON.stringify(temp))
        // this.attributeListNoChild = []
        // temp.forEach(r=>{
        //   if(r.children&&r.children.length){
        //     r.isChild = true
        //     let r2child = false
        //     r.children.forEach(r2=>{
        //       if(r2.children&&r2.children.length){
        //         r2child = true
        //         delete r2.children
        //       }
        //     })
        //     if(r2child){
        //       this.attributeListNoChild.push(JSON.parse(JSON.stringify(r)))
        //     }else{
        //       delete r.children
        //       this.attributeListNoChild.push(JSON.parse(JSON.stringify(r)))
        //     }

        //     delete r.children
        //   }else{
        //     r.isChild = false
        //   }
        // })
        this.attributeList = response.rows;
        // attributeListNoChild
        this.total = response.total;
        this.loading = false;
        // this.$nextTick(()=>{
        //   this.$refs.table.doLayout()
        // })
      });
    },
    // 查询游戏列表
    // 获取列表
    getGameList() {
      gameListApi.getGameList().then((res) => {
        if (res.code == 200) {
          this.gameList = res.rows;
          this.queryParams.gameId = res.rows[0].id;
          this.searchGame = res.rows[0];
          this.getList();
        }
      });
    },
    // 点击了该行
    rowClick(row) {
      this.$refs.table.toggleRowExpansion(row);
    },
    // 懒加载
    tablelazy(row, node, resolve) {
      this.getChild(row, this.attributeListAll, resolve);
    },
    // 找到子级
    getChild(row, list, resolve) {
      list.forEach((r) => {
        if (row.parentId == 0 && row.id == r.id) {
          r.children.forEach((r3) => {
            if (r3.children && r3.children.length) {
              r3.isChild = true;
            }
          });
          resolve(r.children);
        } else {
          if (row.parentId == r.id) {
            r.children.forEach((r2) => {
              if (row.id == r2.id) {
                resolve(r2.children);
              }
            });
          }
        }
      });
    },
    // 新增弹窗中字段类型改变
    fieldTypesChange(e) {
      if (e) {
        this.fieldTypes.map((r) => {
          if (r.key == e) {
            this.form.fieldName = r.name;
          }
        });
        this.form.systemKey = e;
        if (e == "group" && this.form.gameType == 0) {
          this.form.systemKey = "";
          return;
        }
      } else {
        this.form.systemKey = "";
        this.form.fieldName = "";
        this.form.carrier = "";
      }
    },
    // 新增弹窗中  名称改变
    fieldNameInput(e) {
      // 如果是运营商子级，自动生成key
      if (this.form.parentKey == "carrier") {
        // 获取名称的拼音首字母
        let first = pinyin(e, {
          pattern: "first",
          toneType: "none",
          type: "array",
        });
        // first
        console.log("%c Line:228 🍰 first", "color:#fca650", first);
        // 生成key\
        let key = first ? first.join("") : "";
        this.form.systemKey = key;
      }
    },
    // 新增弹窗中， 运营商选择改变
    carrierChange(e) {
      if (e) {
        this.form.systemKey = e + "group";
      }
    },
    // 获取当前游戏的运营商配置
    geiCurGameCarrierOptions() {
      gameDictionaryApi
        .getChildList({
          gameId: this.form.gameId,
          systemKey: "carrier",
        })
        .then((res) => {
          this.carrierOptions = res.rows;
        });
    },
    // 同步官方属性
    asyncAttr() {
      if (!this.searchGame) {
        this.$alert("请先选择游戏！");
        return;
      }
      if (this.searchGame.id == 2) {
        this.$refs.asyncAttr.open(this.searchGame);
      } else if (this.searchGame.id == 5) {
        this.$refs.LOLGetinfoDialog.open("LOL");
      } else if (this.searchGame.id == 3) {
        this.$refs.HPJYGetinfoDialog.open();
      } else if (this.searchGame.id == 29) {
        this.$refs.WWQYGetinfoDialog.open();
      }
    },
    // 快速配置属性
    qtConfig() {
      if (!this.searchGame) {
        this.$alert("请先选择游戏！");
        return;
      }
      this.$refs.copyAttrs.open(this.searchGame);
    },
    //
    // 搜索框选择游戏
    SearchDataGameChange(e) {
      this.gameList.forEach((r) => {
        if (r.id == e) {
          this.searchGame = r;
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // load(tree, treeNode, resolve) {
    //   console.log("%c Line:191 🌮 treeNode", "color:#7f2b82", treeNode);
    //   console.log("%c Line:191 🍊 tree", "color:#4fff4B", tree);
    //   this.loading = true;
    //   gameDictionaryApi.getList({ parentId: tree.id }).then(response => {
    //     resolve(response.rows)
    //     this.loading = false;
    //   });
    // },
    handleAvatarSuccess(res, file) {
      // this.form.imgUrl = res.data.filePath;
      this.$set(this.form, "imgUrl", res.data.filePath);
    },

    // 新增弹窗 游戏改变
    gameChange(e) {
      if (e) {
        this.gameList.forEach((element) => {
          if (element.id == e) {
            this.form.gameName = element.name;
            this.form.gameType = element.type;
          }
        });
      }
    },

    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      (this.form = {
        price: "",
        id: "",
      }),
        this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.attributeList = [];
      this.handleQuery();
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id);
    //   this.single = selection.length !== 1;
    //   this.multiple = !selection.length;
    // },
    /** 新增按钮操作 */
    // handleAdd(row) {
    //   this.reset();

    //   if (row != 0) {
    //     this.topShow = false;
    //     this.form.parentId = row.id;
    //     this.form.parentName = row.fieldName;
    //     this.form.parentKey = row.systemKey;
    //     this.form.gameId = row.gameId;
    //     this.form.gameName = row.gameName;
    //     this.form.gameType = row.type;
    //   } else {
    //     this.topShow = true;
    //     this.form.parentId = 0;
    //     this.form.gameId = this.searchGame.id;
    //     this.form.gameName = this.searchGame.name;
    //     this.form.gameType = this.searchGame.type;
    //   }
    //   this.geiCurGameCarrierOptions();
    //   this.open = true;
    //   this.title = "添加游戏字典";
    // },
    parentChange(e) {
      console.log("%c Line:474 🥝 e", "color:#b03734", e);
      if (e && e.length) {
        this.form.parentId = e[e.length - 1];
      }
    },
    // 回收页面开关改变
    huishouChange(e, row) {
      gameDictionaryApi.edit(row).then((response) => {
        this.$modal.msgSuccess(response.msg);
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.editRow = row;
      this.form = {
        id: row.tenantAttributeSettingsId,
        price: row.price || "",
        gameName: row.gameName,
        fieldName: row.fieldName,
        parentName: row.parentName,
      };
      this.open = true;
      this.title = "修改游戏字典";
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.id != null) {
            gujiaApi.tenantAttributeSettingsEdit(this.form).then((response) => {
              this.loading = false;
              this.$modal.msgSuccess("修改成功");
              // if (this.editRow.parentId != this.form.parentId) {
              //   // 改变了父级id 删除本级里编辑的项
              //   this.resetEcpend(this.editRow, this.form.id);
              //   // 将项目添加到要改后的父级下
              //   let temp =
              //     this.$refs.table.store.states.lazyTreeNodeMap[
              //       this.form.parentId
              //     ];
              //   if (temp && temp.length) {
              //     temp.push(this.form);
              //   } else {
              //     temp = [this.form];
              //   }
              // }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.tenantAttributeSettingsId;
      this.$modal
        .confirm('是否确认删除id为"' + ids + '"的数据项？')
        .then(() => {
          gujiaApi.tenantAttributeSettingsDel(ids).then((res) => {
            this.getList();
            this.$message.success("删除成功");
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>